//
//  B_AddGoodsVC.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/9/2.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_AddGoodsVC.h"
#import "B_AddBankModel.h"
#import "B_ChangeDataFooterView.h"
#import "B_ChangeDataTVC.h"
#import "XGPhotoManager.h"
#import "B_AddGoodsDetailVC.h"
#import "B_AddGoodsModel.h"

@interface B_AddGoodsVC ()<UITextFieldDelegate>
/// 最多图片上传数量
@property (nonatomic, assign) NSInteger count;

@property (nonatomic, strong) BaseTableView * mainView;

@property (nonatomic, strong) NSMutableArray * imageArray;

@property (nonatomic, strong) XGPhotoManager * photoManager;
/// 商品详情的数组 里面存放的是 B_AddGoodsModel  有图没文字,有文字没图.
@property (nonatomic, strong) NSArray * goodsDetailArray;

@end

@implementation B_AddGoodsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    WeakSelf(weSelf, self);
    _count = 6;
    self.imageArray = [NSMutableArray array];
    [self setTitle:@"添加商品"];
    self.view = self.mainView;
    [self setRightTextBarButtonItemWithFrame:CGRectZero title:@"保存" titleColor:[UIColor color_text_red] backImage:@"" selectBackImage:@"" action:^(GUIButton *button) {
        /// TODO:保存
        HXLog(@"保存按钮点击了");
        [weSelf submitImage];
    }];
    
    B_AddBankModel * model0 = [B_AddBankModel initB_AddBankModelWithTitle:@"商品标题" placeholder:@"请输入商品标题" mapword:@"商品名称" alert:@"请输入商品名称"];
    B_AddBankModel * model1 = [B_AddBankModel initB_AddBankModelWithTitle:@"商品简介" placeholder:@"请输入商品简介" mapword:@"商品简介" alert:@"请输入商品简介"];
    B_AddBankModel * model2 = [B_AddBankModel initB_AddBankModelWithTitle:@"价格" placeholder:@"" mapword:@"价格" alert:@"请输入价格"];
    B_AddBankModel * model3 = [B_AddBankModel initB_AddBankModelWithTitle:@"库存" placeholder:@"" mapword:@"库存" alert:@"请输入库存"];
    B_AddBankModel * model4 = [B_AddBankModel initB_AddBankModelWithTitle:@"商品详情" placeholder:@"" mapword:@"商品详情" alert:@"请添加商品详情"];
    NSArray * arr0 = @[model0, model1];
    NSArray * arr1 = @[model2, model3];
    NSArray * arr2 = @[model4];
    self.dataArray = [NSMutableArray arrayWithObjects:arr0, arr1, arr2, nil];
}

- (BaseTableView *)mainView {
    if (!_mainView) {
        WeakSelf(weSelf, self);
        _mainView = [[BaseTableView alloc] init];
        [_mainView setTableViewFrameWithTop:10 left:10 right:-10 bottom:0];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_ChangeDataTVC" bundle:nil] forCellReuseIdentifier:@"B_ChangeDataTVC"];
        _mainView.numberOfSectionsBlock = ^NSInteger(UITableView *tableView) {
            return weSelf.dataArray.count;
        };
        _mainView.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            return ((NSArray *)weSelf.dataArray[section]).count;
        };
        
        _mainView.heightForHeaderBlock = ^CGFloat(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                CGFloat height = (SCREEN_WIDTH - 50) / 3.;
                if (weSelf.imageArray.count >= weSelf.count) {
                    return height * (weSelf.imageArray.count % 3 == 0 ? weSelf.imageArray.count / 3 : weSelf.imageArray.count / 3 + 1) + 50;
                } else {
                    return height * ((weSelf.imageArray.count + 1) % 3 == 0 ? (weSelf.imageArray.count + 1) / 3 : (weSelf.imageArray.count + 1) / 3 + 1) + 50;
                }
            }
            return 10;
        };
        _mainView.viewForHeaderBlock = ^UIView *(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                B_ChangeDataFooterView * view = [B_ChangeDataFooterView initB_ChangeDataFooterView];
                view.count = 3;
                view.imageArray = weSelf.imageArray;
                view.B_lineView.hidden = NO;
                if (weSelf.imageArray.count > 0) {
                    view.B_contentLabel.hidden = YES;
                } else {
                    view.B_contentLabel.text = [NSString stringWithFormat:@"请上传商品图片(最多%ld张)", weSelf.count];
                    view.B_contentLabel.hidden = NO;
                }
                __block NSMutableArray * imageArray = [NSMutableArray array];
                view.deleteAction = ^(NSIndexPath *indexPath) {
                    //                    [imageArray removeObjectAtIndex:indexPath.row];
                    [weSelf.photoManager deleteImageWithIndex:indexPath.row];
                    [weSelf.imageArray removeObjectAtIndex:indexPath.row];
                    [tableView reloadData];
                };
                view.collectionTapAction = ^(NSIndexPath *indexPath) {
                    if (weSelf.imageArray.count == weSelf.count) {
                        //TODO:查看大图
                        
                        
                    } else {
                        if (weSelf.imageArray.count == indexPath.row) { // 选在照片
                            [weSelf alertViewWithTitle:@"请选择" message:@"" buttonsTitles:@[@"相机", @"从相册选择", @"取消"] action:^(NSInteger index) {
                                if (index == 0) {
                                    [weSelf.photoManager openCamereWithController:weSelf withImage:^(UIImage *image) {
                                        [weSelf.imageArray addObject:image];
                                        [tableView reloadData];
                                    }];
                                } else if (index == 1) {
                                    [weSelf.photoManager openMorePhotosWithController:weSelf maxNum:weSelf.count withImage:^(NSArray *imageArr, NSArray *array) {
                                        [weSelf.imageArray removeAllObjects];
                                        [weSelf.imageArray addObjectsFromArray:imageArr];
                                        [tableView reloadData];
                                        imageArray = [NSMutableArray arrayWithArray:array];
                                    }];;
                                }
                            }];
                        } else {
                            //TODO:查看大图
                            
                        }
                    }
                };
                return view;
            }
            return nil;
        };
        
        _mainView.heightForRowBlock = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return 68;
        };
        _mainView.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            
            B_ChangeDataTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_ChangeDataTVC" forIndexPath:indexPath];
            B_AddBankModel * model = weSelf.dataArray[indexPath.section][indexPath.row];
            cell.B_keyLabel.text = model.key_title;
            cell.B_textfield.placeholder = model.placeholder_name;
            cell.B_textfield.text = model.value_name;
            cell.B_textfield.userInteractionEnabled = YES;
            cell.B_rightLabel.hidden = YES;
            cell.B_rightImageView.hidden = YES;
            cell.B_textfield.delegate = weSelf;
            cell.B_textfield.tag = indexPath.section * 100 + indexPath.row;
            cell.B_textfield.textAlignment = NSTextAlignmentLeft;
            if ([model.map_word isEqualToString:@"价格"]) {
                cell.B_textfield.textAlignment = NSTextAlignmentRight;
                cell.B_rightLabel.hidden = NO;
                cell.B_rightImageView.hidden = YES;
                cell.B_textfield.keyboardType = UIKeyboardTypeDecimalPad;
                cell.B_rightLabel.text = @"元";
            } else if ([model.map_word isEqualToString:@"库存"]) {
                cell.B_textfield.textAlignment = NSTextAlignmentRight;
                cell.B_rightLabel.hidden = NO;
                cell.B_rightImageView.hidden = YES;
                cell.B_rightLabel.text = @"件";
                cell.B_textfield.keyboardType = UIKeyboardTypeNumberPad;
            } else if ([model.map_word isEqualToString:@"商品详情"]) {
                cell.B_textfield.userInteractionEnabled = NO;
                cell.B_rightImageView.hidden = NO;
            }
            return cell;
        };
        _mainView.didSelectRow = ^(UITableView *tableView, NSIndexPath *indexPath) {
            B_AddBankModel * model = weSelf.dataArray[indexPath.section][indexPath.row];
            if ([model.map_word isEqualToString:@"商品详情"]) {
                B_AddGoodsDetailVC * detail = [[B_AddGoodsDetailVC alloc] init];
                detail.B_array = weSelf.goodsDetailArray;
                detail.B_addGods = ^(NSArray<B_AddGoodsModel *> *array) {
                    //TODO:这里把商品详情传过来
                    weSelf.goodsDetailArray = array;
                };
                [weSelf pushNextViewController:detail];
                
            }
        };
        
    }
    return _mainView;
}

- (XGPhotoManager *)photoManager {
    if (!_photoManager) {
        _photoManager = [[XGPhotoManager alloc] init];
    }
    return _photoManager;
}

- (void)submitImage {
    if (ISNULL(self.imageArray) || self.imageArray.count == 0) {
        [KeyWindow makeToast:@"请先选择商品图片"];
        return;
    }
    for (NSArray * arr in self.dataArray) {
        for (B_AddBankModel * model in arr) {
            if ([model.map_word isEqualToString:@"商品详情"]) {
                continue;
            }
            if (ISNULL(model.value_name)) {
                [KeyWindow makeToast:model.alert_message];
                return;
            }
        }
    }
    if (ISNULL(self.goodsDetailArray) || self.goodsDetailArray.count == 0) {
        [KeyWindow makeToast:@"请先添加商品详情"];
        return;
    }
    
    NSMutableArray * array = [NSMutableArray array];
    
    [array addObjectsFromArray:self.imageArray];
    for (B_AddGoodsModel * model in self.goodsDetailArray) {
        if (ISNULL(model.B_image)) {
            
        } else {
            [array addObject:model.B_image];
        }
    }
    WeakSelf(weSelf, self);
    [NetworkingManager UploadmoreTaskWithURL:[NSString stringWithFormat:@"%@/yearnfor/inter/goods/addGoodsPicture", ServiceIp] imagesArray:array parameterOfimages:@"files" parametersDict:nil compressionRatio:0.7 succeedBlock:^(NSDictionary *dict) {
        if ([dict[@"code"] isEqualToString:@"20010"]) {
            [weSelf submitData:dict[@"values"]];
        } else {
            [KeyWindow makeToast:dict[@"message"]];
        }
    } failedBlock:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}

- (void) submitData:(NSArray *) array {
    NSMutableDictionary * data = [NSMutableDictionary dictionary];
    for (NSArray * arr in self.dataArray) {
        for (B_AddBankModel * model in arr) {
            if ([model.map_word isEqualToString:@"商品详情"]) {
                continue;
            }
            if ([model.map_word isEqualToString:@"商品名称"]) {
                [data setObject:model.value_name forKey:@"goodsName"];
            } else if ([model.map_word isEqualToString:@"商品简介"]) {
                [data setObject:model.value_name forKey:@"goodsDes"];
            } else if ([model.map_word isEqualToString:@"价格"]) {
                [data setObject:model.value_name forKey:@"goodsPrice"];
            } else if ([model.map_word isEqualToString:@"库存"]) {
                [data setObject:model.value_name forKey:@"goodsStock"];
            }
        }
    }
    [data setObject:getUserId() forKey:@"userId"];
    /// 处理商品图片
    NSMutableArray * goodsPictures = [NSMutableArray array];
    for (int i = 0; i < self.imageArray.count; i++) {
        [goodsPictures addObject:array[i]];
    }
    [data setObject:goodsPictures forKey:@"pictures"];

    /// 处理商品详情
    NSMutableArray * goodsDetail = [NSMutableArray array];
    int index = 0;
    for (B_AddGoodsModel * model in self.goodsDetailArray) {
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        if (ISNULL(model.B_image)) {
            [dict setObject:model.B_text forKey:@"strwords"];
            [dict setObject:@"" forKey:@"strimage"];
        } else {
            [dict setObject:array[index + self.imageArray.count] forKey:@"strimage"];
            [dict setObject:@"" forKey:@"strwords"];
            index ++;
        }
        [goodsDetail addObject:dict];
    }
    [data setObject:goodsDetail forKey:@"itemList"];
    WeakSelf(weSelf, self);
    [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/goods/addGoods" parameters:@{@"str" : [data mj_JSONString]} isCache:NO succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20005"]) {
            [KeyWindow makeToast:@"商品发布成功!"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadGoodsListData" object:nil];
            [weSelf.navigationController popViewControllerAnimated:YES];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
    
    
}


- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    B_AddBankModel * model = self.dataArray[textField.tag / 100][textField.tag % 100];
    if ([model.map_word isEqualToString:@"价格"]) {
        
    } else if ([model.map_word isEqualToString:@"库存"]) {
        
    }
    return YES;
}

- (void) textFieldDidEndEditing:(UITextField *)textField {
    B_AddBankModel * model = self.dataArray[textField.tag / 100][textField.tag % 100];
    model.value_name = textField.text;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
